package com.easyfun.healthmagicbox.comm;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONObject;

import android.content.Context;
import cn.kuaipan.android.openapi.KuaiPanManager;
import cn.kuaipan.android.openapi.KuaiPanTask;

import com.easyfun.healthmagicbox.base.DatabaseAccess;
import com.easyfun.healthmagicbox.base.DatabaseAccessImplementation;
import com.easyfun.healthmagicbox.comm.json.HealthInputListJsonWrapper;
import com.easyfun.healthmagicbox.comm.json.PicturesListJsonWrapper;
import com.easyfun.healthmagicbox.ormlite.DatabaseHelper;
import com.easyfun.healthmagicbox.ormlite.ServerResponseCode;
import com.easyfun.healthmagicbox.pojo.ConstantData;
import com.easyfun.healthmagicbox.pojo.HealthInputData;
import com.easyfun.healthmagicbox.pojo.Picture;
import com.easyfun.healthmagicbox.sync.CommCallback;
import com.j256.ormlite.dao.Dao;

public class PicturesDownloadTask extends BaseCommTask implements DatabaseAccess, KuaiPanTask{

	private String mpersonalID;
	Dao<Picture, Integer> inputdao ;
	public PicturesDownloadTask(Context context, String persionID,
			CommCallback callback) {

		super(context,callback);
		mpersonalID = persionID;
	}

	@Override
	public void run() {
		try {
			
			inputdao = getHelper(mcontext)
					.getPictureDao();
			
			long max = inputdao
					.queryRawValue(
							"select max(syncid) from Picture where personID = ?",
							mpersonalID);

			if (max > -1) {

				JSONObject serializedObj = new JSONObject();
				serializedObj.put("personID", mpersonalID);
				serializedObj.put("syncid", max);				

				Map<String, String> parmas = new HashMap<String, String>();
				parmas.put("jsonstring", serializedObj.toString());
				
				String result = super.uploadByHTTP(parmas,
						ConstantData.PictureDownloadURI);
				
				if (ServerResponseCode.parseOf(result)==ServerResponseCode.FAILED) {
					ccb.setCommResult(this,
							mpersonalID, ServerResponseCode.FAILED);
					return;
				}
				if (ServerResponseCode.parseOf(result)==ServerResponseCode.NOMORE) {
					ccb.setCommResult(this,
							mpersonalID, ServerResponseCode.NOMORE);
					return;
				}
				
				if (result.length()>0) {
					PicturesListJsonWrapper<?> wapper = PicturesListJsonWrapper
							.getInstance(result,PicturesListJsonWrapper.class);
					
					List<Picture> inputlist = wapper.getMpps();
					for (Picture input:inputlist)
					{
						//inputdao.create(input);
						//There is a big problem:
						//If one file has biggest syncid is successfully downloaded.
						// the other files whether are successfully downloaded,
						// they will never be downlaoded again.
						Integer syncid = 0;
						if (input.getId() != null)
						{
							syncid = input.getId();
						}
						List<Picture> exist = inputdao.queryForEq("syncid", syncid);
						if (exist.size() > 0)
							continue;						
						KuaiPanManager.getInstance(mcontext).downloadFile(this,input);
					}
					ccb.setCommResult(this,
							mpersonalID, ServerResponseCode.SUCCESS);
					
				}else
				{
					ccb.setCommResult(this,
							mpersonalID, ServerResponseCode.FAILED);
				}

				return;
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			ccb.setCommResult(this, mpersonalID,
					ServerResponseCode.FAILED);
		} 

	}

	@Override
	public DatabaseHelper getHelper(Context context) {

		return DatabaseAccessImplementation.getInstance().getHelper(mcontext);
	}
	
	public Context getContext()
	{
		return super.mcontext;
	}

	@Override
	public void successfulRun(Object ob) {
		Picture input = (Picture) ob;
		try {
			List<Picture> exist = inputdao.queryForEq("syncid", input.getSyncid());
			if (exist.size() > 0)
				return;	
			inputdao.create(input);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public void failedRun(Object ob) {
		//we could try once more.
	}

}
